import 'package:dio/dio.dart' as dio;
import '../../app/services/userServices.dart';
import '../../app/services/messageUtil.dart';
import 'package:get/get.dart';

class HttpsClient {
  static String domain = "https://apidoc.sjzkeji.com/"; //请求域名

  static dio.Dio dioClient = dio.Dio();
  final userData = UserServices.getUserDataSync();
  HttpsClient() {
    dioClient.options.baseUrl = domain;
    dioClient.options.connectTimeout = const Duration(milliseconds: 5000); //5s 请求超时时间
    dioClient.options.receiveTimeout = const Duration(milliseconds: 5000); //接收数据超时时间
    if(userData != null){
      dioClient.options.headers = {"Authorization": userData["token"]};//全局配置token
    }
  }

  Future get(apiUrl, {Map<String, dynamic>? params}) async {
    try {
      var response = await dioClient.get(apiUrl, queryParameters: params);

      if (response.data['code'] == 401) {
        await UserServices.clearUserData();
        MessageUtil.showError(message: "登录过期");
        Get.offAllNamed("/login");
      }

      return response;
    } catch (e) {
      return null;
    }
  }

  Future post(String apiUrl, {Map? data}) async {

    try {
      var response = await dioClient.post(apiUrl, data: data);
      if (response.data['code'] == 401) {
        await UserServices.clearUserData();
        MessageUtil.showError(message: "登录过期");
        Get.offAllNamed("/login");
      }
      return response;
    } catch (e) {
      // print(e);
      return null;
    }
  }

  Future postFromData(String apiUrl,{required dio.FormData data}) async {
    try {
      var response = await dioClient.post(apiUrl, data: data,options: dio.Options(
        contentType: dio.Headers.multipartFormDataContentType, // 明确指定内容类型
      ),);
      if (response.data['code'] == 401) {
        await UserServices.clearUserData();
        MessageUtil.showError(message: "登录过期");
        Get.offAllNamed("/login");
      }
      return response;
    } catch (e) {
      return null;
    }
  }
}
